/*  This file is part of -_-.

    -_- is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    -_- is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with -_-.  If not, see <http://www.gnu.org/licenses/>.

    Copyright 2012-2013 Oliver Katz */

#include "debug.h"

char *_z_debug_binpath = "";

void _z_dump_line(void *addr)
{
    char tmp[11];
    sprintf(tmp, "0x%08x", (int)addr);
    char *buf[] = {
        "addr2line",
        "-e",
        _z_debug_binpath,
        tmp,
        NULL
    };
    pid_t pid = fork();
    if (pid == 0)
    {
        execvp(buf[0], buf);
    }
    else
    {
        //while(wait(NULL) != pid); // if there are stack trace bugs, this may very well be the problem.
        wait(NULL);
    }
}

void z_dump_stack()
{
#ifdef Z_ENABLE_STACKTRACES
    void *buf[64];
    size_t size = backtrace(buf, 64);
    printf("  - stack trace - %i frames\n", size-1);
    for (size_t i = 1; i < size; i++)
    {
        printf("    - %i - 0x%08x - %s", i-1, buf[i], Z_RED);
        fflush(stdout);
        _z_dump_line(buf[i]);
        fflush(stdout);
        wait(NULL);
        printf("%s", Z_NORMAL);
    }
#endif
}

char *z_basename(char *p)
{
    if (strchr(p, '/') != NULL)
        return strrchr(p, '/')+1;
    else
        return p;
}